<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option :label="item.cate_name" :value="item.id" v-for="item in cataList" :key="item.id"></el-option>

            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="loadArt">筛选</el-button>
            <el-button type="info" size="small" @click="resForm">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubVisible=true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
        <el-table
        border
        stripe
      :data="artList"
      style="width: 100%">
      <el-table-column
        label="文章标题"
        >
        <template v-slot="{row}">
         <el-link type="primary" @click="showD(row.id)">{{row.title}}</el-link>
        </template>
      </el-table-column>
      <el-table-column
        prop="cate_name"
        label="分类"
        >
      </el-table-column>
      <el-table-column
        label="时间">
        <template v-slot='{row}'>
        {{formAt(row.pub_date)}}
        </template>
      </el-table-column>
       <el-table-column
        prop="state"
        label="状态">
      </el-table-column>
       <el-table-column
        label="操作">
        <template v-slot={row}>
          <el-button type="danger" size="mini" @click="delDetail(row.id)">删除</el-button>
        </template>

      </el-table-column>
    </el-table>
      <!-- 分页区域 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="q.pagenum"
          :page-sizes="[2, 3, 5, 20]"
          :page-size="q.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
    </el-pagination>
    </el-card>
          <el-dialog
          fullscreen
        title="发表文章"
        :visible.sync="pubVisible"
        :before-close="handleClose">
      <!-- 渲染列表 -->
      <!-- 发布文章的对话框 -->
        <el-form :model="pubForm" :rules="pubFormRules" ref="pubForm" label-width="100px">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item  label="文章分类" prop="cate_id">
            <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
              <el-option v-for="item in cataList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>

            </el-select>
          </el-form-item>
          <el-form-item  label="文章内容" prop='content'>
            <quill-editor v-model="pubForm.content"
              @blur="$refs.pubForm.validateField('content')" >
              </quill-editor>
          </el-form-item>
          <el-form-item label="文章封面" prop="cover_img">
              <!-- 用来显示封面的图片 -->
              <img v-if="previwe" :src="previwe" alt="" class="cover-img" ref="imgRef" />
              <img v-else src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
              <br />
              <!-- 文件选择框，默认被隐藏 -->
              <input type="file" style="display: none;" accept="image/*" ref="iptFile" @change="hIptFile"/>
              <!-- 选择封面的按钮 -->
              <el-button type="text" @click="$refs.iptFile.click()">+ 选择封面</el-button>

            <el-form-item prop="state">
              <el-button type="primary" @click="hPub('已发布')">发布</el-button>
              <el-button type="info" @click="hPub('存为草稿')">存为草稿</el-button>
            </el-form-item>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 文章详情页的对话框 -->
      <el-dialog
          title="文章预览"
          :visible.sync="DetailVisible"
          width="70%"
          >
          <h1 class="title">{{ detail.title }}</h1>

          <div class="info">
            <span>作者：{{ detail.nickname || detail.username }}</span>
            <span>发布时间：{{ formAt(detail.pub_date)  }}</span>
            <span>所属分类：{{ detail.cate_name }}</span>
            <span>状态：{{ detail.state }}</span>
          </div>

          <!-- 分割线 -->
          <el-divider></el-divider>

          <!-- 文章的封面 -->
          <img :src="'http://www.liulongbin.top:3008' + detail.cover_img" alt="" />

          <!-- 文章的详情 -->
          <div v-html="detail.content" class="detail-box"></div>

</el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  data () {
    return {
      // 文章详情列表的显示与隐藏
      DetailVisible: false,
      // 保存文章列表信息
      detail: {},
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      total: 0,
      pubVisible: false,
      previwe: '',
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: '',
        state: ''
      },
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请选择文章标题', trigger: 'change' }],
        cover_img: [{ required: true, message: '请选择封面', trigger: 'blur' }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      },
      cataList: [],
      artList: []
    }
  },
  methods: {
    // 删除列表数据
    delDetail (id) {
      // 设置弹框确认信息
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 发送请求删除数据
        const { data: res } = await this.$axios.delete('/my/article/info', { params: { id } })
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 删除之后重新获取列表信息，调用请求
        if (this.artList.length === 1 && this.q.pagenum > 1) {
          this.q.pagenum--
        }
        this.loadArt()
      }).catch(() => {

      })
    },
    // 获取详情页的数据，向服务器发送请求
    async showD (id) {
      const { data: res } = await this.$axios.get('/my/article/info', { params: { id } })

      if (res.code !== 0) return
      // 更新文章列表信息
      this.detail = res.data
      // 点击之后显示文章详情页
      this.DetailVisible = true
    },
    // 点击重置按钮，设置绑定事件
    // 重置q对象里面的数据
    // 重新获取列表信息，发送请求
    resForm () {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.loadArt()
    },
    // 分页函数方法设置
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      // 把页面的值赋给原始值，然后重新获取新的 列表
      this.q.pagesize = val
      this.q.pagenum = 1
      this.loadArt()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.q.pagenum = val
      this.loadArt()
    },
    handleClose (done) {
      this.$confirm('您确认要永久关闭吗？', '提示', {
        type: 'warning'
      })
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    async loadCatalist () {
      const { data: res } = await this.$axios.get('/my/cate/list')
      this.cataList = res.data
    },
    // 设置文章封面
    hIptFile (e) {
      const file = e.target.files[0]
      if (file) {
        this.pubForm.cover_img = file
        this.previwe = URL.createObjectURL(file)
        // const fr = new FileReader()
        // fr.readAsDataURL(file)
        // fr.onload = () => {
        //   this.previwe = e.target.result
        // }
      } else {
        this.pubForm.cover_img = ''
        this.previwe = ''
      }
      this.$refs.pubForm.validateField('cover_img')
    },
    // 发送文章列表，提交发布
    hPub (state) {
      this.pubForm.state = state
      console.log(state)
      this.$refs.pubForm.validate(async valid => {
        if (!valid) return
        // 发送请求，axios默认的请求头是application/JSON
        // 接口文档里面的是Form-Data模式
        // 转换方法，new formData实例
        const fd = new FormData()
        // fd上面有一个方法append添加数据
        //  fd.append('title',this.pubForm.title)
        // 可以循环此对象获取数据
        for (const k in this.pubForm) {
          fd.append(k, this.pubForm[k])
        }
        // 或者循环数组。把源对象转换成数组
        // Object.keys(this.pubForm).forEach(k => fd.append(k, this.pubForm[k]))
        const { data: res } = await this.$axios.post('/my/article/add', fd)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.pubVisible = false
        // 清空表单
        this.$refs.pubForm.resetFields()
        this.previwe = ''
        // 封面里面的图片提交之后清空
        this.$refs.iptFile.value = ''
        this.loadArt()
      })
    },
    // 获取列表文章
    async loadArt () {
      const { data: res } = await this.$axios.get('/my/article/list', { params: this.q })
      this.total = res.total
      this.artList = res.data
      // 获取页面总条数可以打印res看看里面的数据有一个total
      this.total = res.total
    },
    formAt (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  created () {
    this.loadCatalist()
    this.loadArt()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
//scoped作用：让当前样式在当前组件内有效果，只对当前template中的元素有效
//scoped原理：
//1.只给当前组件内template中的所有标签加上[data-v-hash]属性
//2.给当前组件内的style中的所有的选择器加上属性交集选择器 .qi-editor[data-v-hash]
//3.注意：只会给当前的template中的标签加上data-v-hash属性，如果是组件，则只会给组件的跟标签加data-v-hash
//解决方法
//1.直接删除scoped但是样式会相互影响，不建议使用
//2.给标签添加深度选择器 /deep/选择器
/deep/ .ql-editor{
  height: 300px;
}
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
